package org.sklse.learningassistant.service;


import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImageService {


    public String uploadImage(String imgStr,String key){
        System.out.println(imgStr);
        if(imgStr==null){
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();

        try{
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

//            String key = IDUtils.genImageName();
            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);

            //...生成上传凭证，然后准备上传
            String accessKey = "slBR7jwpCvhA04Sy8jUp_n8RoDwnWt8SEL1gbyJv";
            String secretKey = "Z_--bIBWfD7_mzmq-KB02SY6308PfLKL2_lHBfMa";
            String bucket = "learn";

            //默认不指定key的情况下，以文件内容的hash值作为文件名

            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(b);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(byteInputStream,key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return "http://oxe0ng04h.bkt.clouddn.com/"+putRet.key ;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public String convertToImage(String imgStr, String key){
        String picUrlFromQiniu = "";
        System.out.println(imgStr);
        if(imgStr == null){
            return null;
        }
        String tempStr = "";
        for(int i = 0; i < imgStr.length(); i++){
            if(imgStr.charAt(i) == ' '){
                // tempStr.replace(tempStr.charAt(i),'+');
                tempStr += '+';
            }else {
                tempStr += imgStr.charAt(i);
            }
        }

        System.out.println(tempStr);

        BASE64Decoder decoder = new BASE64Decoder();
        try{
            byte[] b = decoder.decodeBuffer(tempStr.replace("data:image/png;base64,",""));
            for(int i = 0; i < b.length; i++){
                if(b[i] < 0){
                    b[i] += 256;
                }
            }

            //add at 2017-12-02
            // String key = "test111";
            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);

            //...生成上传凭证，然后准备上传
            // String accessKey = "slBR7jwpCvhA04Sy8jUp_n8RoDwnWt8SEL1gbyJv";
            // String secretKey = "Z_--bIBWfD7_mzmq-KB02SY6308PfLKL2_lHBfMa";
//            String accessKey = "R-VySGh3wLO40m5r3WEkaLNhUQM2xUp5yiYY2DmR";
//            String secretKey = "ZPzvJiPq9gY9q8rmro2RQOQMyALlqoOTWohh7uzZ";
//            String bucket = "bucket01";
            String accessKey = "slBR7jwpCvhA04Sy8jUp_n8RoDwnWt8SEL1gbyJv";
            String secretKey = "Z_--bIBWfD7_mzmq-KB02SY6308PfLKL2_lHBfMa";
            String bucket = "learn";
            //默认不指定key的情况下，以文件内容的hash值作为文件名

            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(b);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            System.out.println(upToken);
            Response response = uploadManager.put(byteInputStream,key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //picUrlFromQiniu = "http://ot0m3go2y.bkt.clouddn.com/"+putRet.key;
            picUrlFromQiniu = "http://oxe0ng04h.bkt.clouddn.com/"+ putRet.key;
            System.out.println(picUrlFromQiniu);
            //end here


            /*
            File file = new File(savePath + "test1.png");
            OutputStream out = new FileOutputStream(file);
            out.write(b);
            out.flush();
            out.close();
            */

        }catch (Exception e){
            e.printStackTrace();
            return null ;
        }

        return picUrlFromQiniu;

    }

    public boolean savePicture(MultipartHttpServletRequest request){
        try{
            MultiValueMap<String,MultipartFile> map = request.getMultiFileMap();// 为了获取文件，这个类是必须的
            List<MultipartFile> list = map.get("uploadify");// 获取到文件的列表
            String path= "I:/ionic projects/sklse-LearningAssistant-master_2/LearningAssistant/src/main/resources/img/";
            List<String>filenameList= new ArrayList<>();//
            // 将图片进行存储
            for (MultipartFile mFile : list) {
                String originalFileName= mFile.getOriginalFilename();//获取文件名称
                filenameList.add(originalFileName);
                byte[] bytes = mFile.getBytes();//获取字节数组
                String filePath= path+ File.separator+ originalFileName;
                FileOutputStream fos= new FileOutputStream(new File(filePath)); //写出到文件
                fos.write(bytes);
                fos.flush();
                fos.close();
            }

        }catch (Exception e){

        }
        return true;
    }
}
